package com.step.ems.pages.common

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.king.ultraswiperefresh.UltraSwipeRefreshState
import com.step.ems.common.RefreshType
import com.step.ems.common.UiState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

abstract class PageViewModel<T> : ViewModel() {
    var pageIndex = 1

    protected val _uiState = MutableStateFlow<UiState>(UiState.Loading())
    val uiState get() = _uiState.asStateFlow()

    val pullRefreshState = UltraSwipeRefreshState(isRefreshing = false, isLoading = false)

    protected val _data = MutableStateFlow<List<T>>(emptyList())
    val data get() = _data.asStateFlow()

    init {
        observeState()
    }

    private fun observeState() = viewModelScope.launch {
        _uiState.collect { state ->
            when (state) {
                is UiState.Loading -> {
                    if (state.type == RefreshType.Pull) {
                        pullRefreshState.isRefreshing = true
                    }
                }

                is UiState.Success, is UiState.Error -> {
                    pullRefreshState.isRefreshing = false
                }

                else -> Unit
            }
        }
    }
}